package com.bayi.storage.utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.IBinder;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.bayi.storage.base.BaseApplication;

/**
 * Created by guoping on 16/5/27.
 */
public class UIUtil {

    public static Context getAppContext() {
        return BaseApplication.getApp().getApplicationContext();
    }


    public static int dp2px(float dp) {
        final float scale = BaseApplication.getApp().getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public static int dp2px(double dp) {
        final float scale = BaseApplication.getApp().getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public static float px2dp(int px) {
        final float scale = BaseApplication.getApp().getResources().getDisplayMetrics().density;
        return (px / scale + 0.5f);
    }

    public void measureView(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }


    @TargetApi(VERSION_CODES.LOLLIPOP)
    public static void setStatusBarColor(Activity activity, int statusColor) {

        if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            activity.getWindow().setStatusBarColor(statusColor);
            return;
        }

        if (Build.VERSION.SDK_INT >= VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
            ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
            View statusBarView = new View(activity);
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    getStatusBarHeight(activity));
            statusBarView.setBackgroundColor(statusColor);
            contentView.addView(statusBarView, lp);
        }

    }

    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    public static int getColor(int id) {
        return BaseApplication.getApp().getApplicationContext().getResources().getColor(id);
    }

    public static String getString(int id) {
        return BaseApplication.getApp().getResources().getString(id);
    }

    public static int getDimen(int id) {
        return BaseApplication.getApp().getResources().getDimensionPixelSize(id);
    }

    public static float getDimenDp(int id) {
        return px2dp(getDimen(id));
    }

    public static void setLayoutWidth(View view, int width) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (params != null) {
            params.width = width;
            view.setLayoutParams(params);
        }
    }

    public static void setLayoutWidth(View view, float widthDp) {
        setLayoutWidth(view, dp2px(widthDp));
    }

    public static void setLayoutWidthResource(View view, int id) {
        setLayoutWidth(view, getDimen(id));
    }

    public static void setLayoutHeight(View view, int height) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (params != null) {
            params.height = height;
            view.setLayoutParams(params);
        }
    }

    public static void setLayoutHeight(View view, float heightDp) {
        setLayoutHeight(view, dp2px(heightDp));
    }

    public static void setLayoutHeightResource(View view, int id) {
        setLayoutHeight(view, getDimen(id));
    }

    public static void setLayoutSize(View view, double width, double height) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (params != null) {
            params.width = dp2px(width);
            params.height = dp2px(height);
            view.setLayoutParams(params);
        }
    }

    public static void setLayoutSizeUtil(View view, int width, int height) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (params != null) {
            params.width = width;
            params.height = height;
            view.setLayoutParams(params);
        }
    }

    /**
     * 设置自定义View状态栏颜色
     *
     * @param view
     * @param color
     * @param isDrawable
     */
    @SuppressLint("NewApi")
    public static void setCustomStatusColor(View view, int color, boolean isDrawable) {
        if (isDrawable) {
            view.setBackground(getDrawable(color));
        } else {
            view.setBackgroundColor(getColor(color));
        }
    }

    public static Drawable getDrawable(Integer id) {
        if (id == null) {
            return null;
        }
        return ContextCompat.getDrawable(BaseApplication.getApp(), id);
    }

    /**
     * 微信分享角边显示黑色问题
     * Drawable转换为Bitmap
     *
     * @param drawableId
     * @return
     */
    public static Bitmap drawableToBitamp(Integer drawableId) {
        Drawable drawable = getDrawable(drawableId);
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 注意，下面三行代码要用到，否在在View或者surfaceview里的canvas.drawBitmap会看不到图
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }

    public static Bitmap getBitmap(int resId) {
        BitmapDrawable drawable = (BitmapDrawable) getDrawable(resId);
        return drawable.getBitmap();
    }

    public static void setCompoundDrawables(TextView textView, Integer left, Integer top, Integer right, Integer bottom) {
        setCompoundDrawables(textView, getDrawable(left), getDrawable(top), getDrawable(right), getDrawable(bottom));
    }

    public static void setCompoundDrawables(TextView textView, Drawable left, Drawable top, Drawable right, Drawable bottom) {
        if (left != null) {
            left.setBounds(0, 0, left.getMinimumWidth(), left.getMinimumHeight());
        }
        if (top != null) {
            top.setBounds(0, 0, top.getMinimumWidth(), top.getMinimumHeight());
        }
        if (right != null) {
            right.setBounds(0, 0, right.getMinimumWidth(), right.getMinimumHeight());
        }
        if (bottom != null) {
            bottom.setBounds(0, 0, bottom.getMinimumWidth(), bottom.getMinimumHeight());
        }
        textView.setCompoundDrawables(left, top, right, bottom);
    }


    public static void showKeyboard(EditText edit) {
        InputMethodManager imm = (InputMethodManager) BaseApplication.getApp().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(edit, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    public static void hideKeyboard(Activity activity) {
        hideKeyboardWithActivityOrDialog(activity);
    }

    public static void hideKeyboard(View view) {
        hideKeyboardWithActivityOrDialog(view);
    }

    public static void hideKeyboard(Dialog dialog) {
        hideKeyboardWithActivityOrDialog(dialog);
    }

    /**
     * 判断输入法是否显示
     *
     * @param view
     */
    private static void hideKeyboardWithActivityOrDialog(Object view) {
        InputMethodManager localInputMethodManager =
                (InputMethodManager) BaseApplication.getApp().getSystemService(Context.INPUT_METHOD_SERVICE);

        View currentFocus = null;
        if (ClassUtils.isSubClass(view.getClass(), Dialog.class)) {
            currentFocus = ((Dialog) view).getCurrentFocus();
        } else if (ClassUtils.isSubClass(view.getClass(), Activity.class)) {
            currentFocus = ((Activity) view).getCurrentFocus();
        }
        if (currentFocus != null) {
            IBinder localIBinder = currentFocus.getWindowToken();
            if (localIBinder != null) {
                localInputMethodManager.hideSoftInputFromWindow(localIBinder, 0);
            }
            currentFocus.clearFocus();
        }
    }
}
